#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Image.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    paint_rect.setRect(ui->Display_screen->x()-1,ui->Display_screen->y()-1,ui->Display_screen->width()+2,ui->Display_screen->height()+2);
    Initalize();
    this->setWindowTitle("PhotoStall");


    //按钮上放置图片
    QIcon con_Cut(":/img/Cut.png");
    QIcon con_Rotate_Left(":/img/Rotate_Left.png");
    QIcon con_Rotate_Right(":/img/Rotate_Right.png");
    QIcon con_Turned_Over(":/img/Turned_Over.png");
    QIcon con_Left_to_Right(":/img/Left_to_Right.png");
    QIcon con_upanddown(":/img/upanddown.png");
    QIcon con_Resize(":/img/Resize.png");
    QIcon con_Make_it_again(":/img/Make_it_again.png");
    QIcon con_Un_Do(":/img/Un_Do.png");


    ui->Cut->setIcon(con_Cut);
    ui->Rotate_Left->setIcon(con_Rotate_Left);
    ui->Rotate_Right->setIcon(con_Rotate_Right);
    ui->Turned_Over->setIcon(con_Turned_Over);
    ui->Left_to_Right->setIcon(con_Left_to_Right);
    ui->upanddown->setIcon(con_upanddown);
    ui->Resize->setIcon(con_Resize);
    ui->Make_it_again->setIcon(con_Make_it_again);
    ui->Un_Do->setIcon(con_Un_Do);

    ui->Cut->setToolTip("裁剪");
    ui->Rotate_Left->setToolTip("向左旋转");
    ui->Rotate_Right->setToolTip("向右旋转");
    ui->Turned_Over->setToolTip("翻转");
    ui->Left_to_Right->setToolTip("左右变换");
    ui->upanddown->setToolTip("上下变换");
    ui->Resize->setToolTip("放缩");
    ui->Make_it_again->setToolTip("还原");
    ui->Un_Do->setToolTip("撤销");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::Initalize()
{
    ui->Brightness_adjuster->setValue(0);
    ui->warm_cold_change->setValue(0);
    pix_fix = pix_src;
    paint_x_exp = paint_x =paint_rect.x()  ;
    paint_y_exp = paint_y = paint_rect.y();
    paint_w_exp = paint_w = paint_rect.width();
    paint_h_exp = paint_h = paint_rect.height();
    pix_sx = 0;
    pix_sy = 0;
}

void MainWindow::Reset_photo()
{
    img[0] = img_qrc;
    i = 0;
    j = 0;
    full = false;
    Initalize();
}


void MainWindow::Update_photo()
{
    paint_w_exp = pix_fix.width();
    paint_h_exp = pix_fix.height();

    paint_y = paint_y_exp;
    if(paint_y_exp < paint_rect.y())  //期望的起点超出画布上限
    {
        pix_sy =  paint_rect.y() - paint_y_exp;
        pix_sy = pix_sy>pix_fix.height()?pix_fix.height():pix_sy;
        paint_y = paint_rect.y();
    }
    else
    {
        pix_sy = 0;
    }

    if(paint_y>=(paint_rect.y()+paint_rect.height()-1))
    {
        paint_y = (paint_rect.y()+paint_rect.height()-1);
    }
    paint_h_exp -= pix_sy;
    paint_h_exp = paint_h_exp>( paint_rect.height()+paint_rect.y()-paint_y )?(paint_rect.height()+paint_rect.y()-paint_y):paint_h_exp;
    paint_x = paint_x_exp;
    if(paint_x < paint_rect.x())
    {
        pix_sx =  paint_rect.x() - paint_x;
        pix_sx = pix_sx>pix_fix.width()?pix_fix.width():pix_sx;
        paint_x = paint_rect.x();
    }
    else
    {
     pix_sx = 0;
    }
    if(paint_x>=(paint_rect.x()+paint_rect.width()-1))
    {
        paint_x = (paint_rect.x()+paint_rect.width()-1);
    }
    paint_w_exp -= pix_sx;
    paint_w_exp = paint_w_exp>( paint_rect.width()+paint_rect.x()-paint_x )?(paint_rect.width()+paint_rect.x()-paint_x):paint_w_exp;
    paint_h = paint_h_exp;
    paint_w = paint_w_exp;

    qDebug()<<paint_rect;
    qDebug()<<paint_x<<paint_y<<paint_w<<paint_h<<pix_fix<<pix_sx<<pix_sy;
}

void MainWindow::paintEvent(QPaintEvent * event)
{
   QPainter painter(this);
   painter.setRenderHints(QPainter::SmoothPixmapTransform|QPainter::Antialiasing|QPainter::TextAntialiasing);
   painter.drawRect(paint_rect.x(),paint_rect.y(),paint_rect.width(),paint_rect.height());
   painter.drawTiledPixmap(paint_x,paint_y,paint_w,paint_h,pix_fix,pix_sx,pix_sy);


}

void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton && paint_rect.contains(event->pos()))
    {
        Reset_photo();
        Update_photo();
        this->update();
    }
}

bool MainWindow::event(QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress )
    {
        QMouseEvent *mouse = dynamic_cast<QMouseEvent* >(event);
        if(mouse->button()==Qt::LeftButton && paint_rect.contains(mouse->pos()))
        {
            mouse_press_flag = true;
            QApplication::setOverrideCursor(Qt::OpenHandCursor);
            mouse_pos_pre = mouse->pos();
        }
        qDebug()<<"MouseButtonPress";
    }
    else if(event->type() == QEvent::MouseButtonRelease)
    {
        QMouseEvent *mouse = dynamic_cast<QMouseEvent* >(event);
        if(mouse->button()==Qt::LeftButton && mouse_press_flag )
        {
            QApplication::setOverrideCursor(Qt::ArrowCursor);
            mouse_press_flag=false;
        }
        qDebug()<<"MouseButtonRelease";
    }

    if(event->type() == QEvent::MouseMove)
        {
            if(mouse_press_flag)
            {
                QMouseEvent *mouse = dynamic_cast<QMouseEvent* >(event);
                mouse_pos_cur = mouse->pos();
                int dx = mouse_pos_cur.x() - mouse_pos_pre.x();
                int dy = mouse_pos_cur.y() - mouse_pos_pre.y();
                mouse_pos_pre = mouse_pos_cur;
                paint_x_exp += dx;
                paint_y_exp += dy;
                Update_photo();
                this->update();
            }
            qDebug()<<"MouseMove";
        }
    return QWidget::event(event);
}

//打开文件
void MainWindow::on_File_Open_triggered()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"),"/home",tr("Images (*.bmp)"));
    QImage image=QImage(filename);
    QByteArray ba = filename.toLatin1();
    last_filename=ba.data();
    img_qrc.ReadBMP(last_filename);
    img[0] = img_qrc;
    i = 0;
    j = 0;
    full = false;
    pix_src = QPixmap::fromImage(img_qrc);
    pix_fix = pix_src;
    Update_photo();
    ui->w_of_Image_2->setNum(img[i].Width());
    ui->h_of_Image_2->setNum(img[i].Height());
}

//保存
void MainWindow::on_File_Save_triggered()
{
    img[i].WriteBMP(last_filename);
    ui->statusbar->showMessage("文件保存成功",3000);
}                                           //  双线性插值法  如何更新图片是个问题 可以考虑重载图片

//另存为
void MainWindow::on_Save_As_triggered()
{
    QString pathsave = QFileDialog::getSaveFileName(this,"Save","/home","Images (*.bmp)");
    QByteArray ba = pathsave.toLatin1();
    img[i].WriteBMP(ba.data());
    ui->statusbar->showMessage("文件另存成功",3000);
}

//每次动作时引用增加，用来撤销
void MainWindow::ijia(){
    if(i==9){
        full = true;
        img[0]=img[9];
        i=0;
    }
    else {
        img[i+1]=img[i];
        i++;
        k = i;
    }
    if (full)
    {
        j=(i+1)%10;
    }
}

//撤销
void MainWindow::before(){
    if(i==0&&full){i=9;}
    else if(i==j){
        ui->statusbar->showMessage("已超过撤销限制次数，无法撤销",3000);
    }
    else {i--;}
}

//显示下一步操作
void MainWindow::next(){
    if (full&&i+1!=j)
        i++;
    else if (i < k)
        i++;
    else ui->statusbar->showMessage("您没有更多操作啦！",3000);
}

//展示模块
void MainWindow::Show_Changed_Image()
{
    pix_fix = QPixmap::fromImage(img[i]);
    Update_photo();
    this->update();
    ui->w_of_Image_2->setNum(img[i].Width());
    ui->h_of_Image_2->setNum(img[i].Height());
}

//左转
void MainWindow::on_Rotate_Left_clicked()
{
    ijia();
    img[i].Rotate_Left();
    Show_Changed_Image();
}

//右转
void MainWindow::on_Rotate_Right_clicked()
{
     ijia();
    img[i].Rotate_Right();
   Show_Changed_Image();
}

//转180度
void MainWindow::on_Turned_Over_clicked()
{
     ijia();
    img[i].Turned_Over();
  Show_Changed_Image();
}

//左右翻转
void MainWindow::on_Left_to_Right_clicked()
{
     ijia();
    img[i].Flip(0);
    Show_Changed_Image();
}

//上下反转
void MainWindow::on_upanddown_clicked()
{
     ijia();
    img[i].Flip(1);
    Show_Changed_Image();
}

//亮度调节模块：滑动显示
void MainWindow::on_Brightness_adjuster_valueChanged(int value)
{
    img[i].operator +(value);
    Show_Changed_Image();
    img[i]=img[i-1];
    last_time_brt = value;
}
//亮度调节模块：点击时副本
void MainWindow::on_Brightness_adjuster_sliderPressed()
{
    ijia();
}
//亮度调节模块：释放时生成
void MainWindow::on_Brightness_adjuster_sliderReleased()
{
    img[i].operator +(last_time_brt);
    Show_Changed_Image();
}

//冷暖调调节模块：滑动显示
void MainWindow::on_warm_cold_change_valueChanged(int value)
{
    img[i].warm_cold_change(value);
    Show_Changed_Image();
    img[i]=img[i-1];
    last_time_color = value;
}
//冷暖调调节模块：点击时副本
void MainWindow::on_warm_cold_change_sliderPressed()
{
    ijia();
}
//冷暖调调节模块：释放时生成
void MainWindow::on_warm_cold_change_sliderReleased()
{
    img[i].warm_cold_change(last_time_color);
    Show_Changed_Image();
}

//撤销模块
void MainWindow::on_Un_Do_clicked()
{
    before();
    Show_Changed_Image();
}

//还原模块
void MainWindow::on_Make_it_again_clicked()
{
    next();
    Show_Changed_Image();
}

//黑白化模块
void MainWindow::on_gray2bw_editingFinished()
{
    ijia();
   img[i].gray2bw(ui->gray2bw->value());
   Show_Changed_Image();
}

//拉伸缩放模块
void MainWindow::on_Resize_clicked()
{
    ijia();
    img[i].Resize(ui->Change_h->value(),ui->Change_w->value());
    Show_Changed_Image();
}


//裁剪模块
void MainWindow::on_Cut_clicked()
{
     ijia();
     int x1 = ui->X1->value();
     int y1 = ui->Y1->value();
     int x2 = ui->X2->value();
     int y2 = ui->Y2->value();
     if(x1>=x2||y1>=y2||y2>img[i].Height()||x2>img[i].Width()){
        ui->statusbar->showMessage("输入数据不合法！请检查是否超过最大值",3000);
        return;
     }
     img[i].Cut(x1,y1,x2,y2);
     Show_Changed_Image();
}

//灰度图模块
void MainWindow::on_gray_clicked()
{
    ijia();
    img[i].gray();
    Show_Changed_Image();
}

//均值
void MainWindow::on_mean_clicked()
{
    ijia();
    img[i].MeanFilter(3);
    Show_Changed_Image();
}

//中值
void MainWindow::on_median_clicked()
{
    ijia();
    img[i].MedianFilter(3);
    Show_Changed_Image();
}

//黑白度变化
void MainWindow::on_to_GrayandWhite_clicked()
{
    ijia();
   img[i].gray2bw(ui->gray2bw->value());
   Show_Changed_Image();
}

//凹透变化
void MainWindow::on_Convex_clicked()
{
    ijia();
    img[i].to_barrel();
    Show_Changed_Image();
}

// 边 缘 检 测
void MainWindow::on_Edge_detection_clicked()
{
    ijia();
    img[i]=sobel(img[i-1]);
    Show_Changed_Image();

}

